package org.example.orders.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

/*
    针对本地所有的资源被 sentinel 控制之后,出现的  流控异常,熔断异常,授权异常,热点数据异常
    专门处理
 */
@Component
public class MyExceptionHandler implements BlockExceptionHandler {
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        /*
            前两个参数代表的是请求和响应相关的对象
            第三个参数代表的就是 sentinel 提供的异常对象
         */
        // 判断当前异常的具体类型
        String msg = null;
        if(e instanceof FlowException){//流控
            msg = "手速太快了,慢点刷即可...";
        }/*else if(e instanceof ParamFlowException){//热点 不可用 只能走全局变量异常
            msg = "这个数据太热了,让它静静...";
        }*/else if(e instanceof DegradeException){//熔断
            msg = "走备胎了...";
        }else if(e instanceof AuthorityException){//授权
            msg = "您的级别不够...";
        }else {
            msg = "被系统制裁了...";
        }
        httpServletResponse.setContentType("text/html;charset=utf-8");
        httpServletResponse.getWriter().println(msg);
    }
}

